package com.example.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Aspect
@Component
public class LogAspect {



    @Before("@annotation(com.example.aop.Action)")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 类名
        String typeName = signature.getDeclaringTypeName();
        // 方法名
        String methodName = signature.getMethod().getName();
        // 通知消息
        String adviceMessage = String.format("  ->%s: calling %s.%s(%s)",
                "注解方式拦截",
                typeName, methodName, Stream.of(joinPoint.getArgs()).map(Object::toString).collect(Collectors.joining(",")));
        System.out.println(adviceMessage);
    }

    @After("execution(public * com.example.aop.*.*(..))")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String typeName = signature.getDeclaringTypeName();
        String methodName = signature.getMethod().getName();
        System.out.printf("  ->%s: returning from %s.%s(%s)%n", "表达式方式拦截",
                typeName, methodName, Stream.of(joinPoint.getArgs()).map(Object::toString).collect(Collectors.joining(",")));
    }


}
